package com.ruoyi.system.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.OrderStatusEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.Commodity;
import com.ruoyi.system.domain.Order;
import com.ruoyi.system.domain.Shop;
import com.ruoyi.system.domain.UserOrder;
import com.ruoyi.system.domain.dto.PlaceOrder;
import com.ruoyi.system.mapper.CommodityMapper;
import com.ruoyi.system.mapper.OrderMapper;
import com.ruoyi.system.mapper.UserOrderMapper;
import com.ruoyi.system.service.ICommodityService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * 商品Service业务层处理
 *
 * @author ruoyi
 * @date 2023-02-20
 */
@Service
public class CommodityServiceImpl implements ICommodityService
{
    @Autowired
    private CommodityMapper commodityMapper;
    @Autowired
    private OrderMapper orderMapper ;
    @Autowired
    private UserOrderMapper userOrderMapper ;

    /**
     * 查询商品
     *
     * @param id 商品主键
     * @return 商品
     */
    @Override
    public Commodity selectCommodityById(Long id)
    {
        return commodityMapper.selectCommodityById(id);
    }

    /**
     * 查询商品列表
     *
     * @param commodity 商品
     * @return 商品
     */
    @Override
    public List<Commodity> selectCommodityList(Commodity commodity)
    {
        if (Objects.isNull(commodity.getOwnerShop())){
            throw new ServiceException("请选择门店！") ;
        }
        if (StringUtils.isNotBlank(commodity.getRoles())){
            if (commodity.getRoles().contains(UserConstants.SHOP_OWNER)){
                Long ownerShop = commodity.getOwnerShop();
                Long userId = SecurityUtils.getUserId();
                List<Shop> list = commodityMapper.checkShopOwner(ownerShop,userId) ;
                if (CollectionUtils.isEmpty(list)){
                    throw new ServiceException("请选择门店！") ;
                }
            }
        }
        return commodityMapper.selectCommodityList(commodity);
    }

    /**
     * 新增商品
     *
     * @param commodity 商品
     * @return 结果
     */
    @Override
    public int insertCommodity(Commodity commodity)
    {
        return commodityMapper.insertCommodity(commodity);
    }

    /**
     * 修改商品
     *
     * @param commodity 商品
     * @return 结果
     */
    @Override
    public int updateCommodity(Commodity commodity)
    {
        return commodityMapper.updateCommodity(commodity);
    }

    /**
     * 批量删除商品
     *
     * @param ids 需要删除的商品主键
     * @return 结果
     */
    @Override
    public int deleteCommodityByIds(Long[] ids)
    {
        return commodityMapper.deleteCommodityByIds(ids);
    }

    /**
     * 删除商品信息
     *
     * @param id 商品主键
     * @return 结果
     */
    @Override
    public int deleteCommodityById(Long id)
    {
        return commodityMapper.deleteCommodityById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void generateOrder(PlaceOrder placeOrder) throws Exception {
        if (Objects.isNull(placeOrder)){
            throw new Exception("下单商品不能为空!") ;
        }
        if (Objects.isNull(placeOrder.getAllMoney())){
            throw new Exception("总金额不能为空!") ;
        }
        if (CollectionUtils.isEmpty(placeOrder.getCommodities())){
            throw new Exception("商品信息不能为空!") ;
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Order order = new Order();
        /**设置订单信息*/
        order.setAllMoney(placeOrder.getAllMoney().setScale(2, BigDecimal.ROUND_HALF_UP));
        order.setShopId(placeOrder.getShopId());
        order.setOrderNo(UUID.randomUUID().toString().substring(0,8));
        order.setShopName(placeOrder.getShopName());
        order.setCreateTime(new Date());
        order.setCreateBy(SecurityUtils.getUsername());
        order.setStatus(OrderStatusEnum.ORDER_WAIT_CONFIRM_ADDRESS.getCode());
        /**设置用户信息*/
        order.setUserId(loginUser.getUserId());
        order.setUserName(loginUser.getUser().getNickName());
        order.setUserPhone(loginUser.getUser().getPhonenumber());
        /**商品信息处理*/
        List<Commodity> commodities = placeOrder.getCommodities();
        StringBuilder sb = new StringBuilder();
        for (Commodity commodity : commodities) {
            /**处理订单信息*/
            sb.append("商品名称:").append(commodity.getName()).append("  数量:").append(commodity.getNumber()).append("___") ;
            int i = this.commodityMapper.payCommodity(commodity);
            if (i == 0 || i > 1){
                throw new Exception("商品数量不足！") ;
            }
        }
        sb.append("\n").append("总金额:").append(placeOrder.getAllMoney()) ;
        order.setCommodityDescribe(sb.toString());
        /**生成订单*/
        orderMapper.insertOrder(order) ;
        /**生成用户订单表*/
        UserOrder userOrder = new UserOrder();
        userOrder.setUserId(loginUser.getUserId());
        userOrder.setOrderId(order.getId());
        userOrderMapper.insertUserOrder(userOrder);
    }
}
